#!/usr/bin/env python
import os
import subprocess
import sys
import tarfile
import shutil

class LabStability:
    def __init__(self, build, iterations):
        self.build = build
        self.full_list = None
        self.urban_list = None
        self.output_dir = None
        self.iterations = iterations
        self.flowtool_path = "/tmp/flowtool/flowtool"
        self.working_dir = build + "/capreader"
        self.capreader_path = None

    def extract_build(self):
        """ Extracts a NAVL build to the builds dir """
        build_destination = "/root/builds/"
        if os.path.isdir(self.build[:-7]):
            shutil.rmtree(self.build[:-7])
        if tarfile.is_tarfile(self.build):
            try:
                print "Extracting" + sys.argv[1]
                new_build = tarfile.open(str(self.build))
                new_build.extractall(path=build_destination)
                new_build.close()
                self.capreader_path = str(self.build[:-7]) + "/capreader"
                working_dir = str(self.capreader_path) + "/lab_stability"
                os.mkdir(working_dir)
                self.output_dir = working_dir
            except Exception, error_msg:
                print error_msg
        else:
            print "Not a file: %s" % self.build

    def create_file_list(self):
        smoke_traces_dir = "/dev/shm/Traces"
        self.full_list = self.output_dir + "/full_list.txt"
        if os.path.isfile(self.full_list):
            os.remove(self.full_list)
        with open(str(self.full_list), "w") as outfile:
            for num in xrange(self.iterations):
                for path, dirs, files in os.walk(smoke_traces_dir):
                    for f in files:
                        f = os.path.join(path, f)
                        if f.endswith(".pcap") or f.endswith(".cap"):
                            if os.path.isfile(f):
                                outfile.write(f + '\n')
                            else:
                                print "not a file"
        outfile.close()

    def create_file_list_urban(self, file_list):
        urban_traces_dir = "/root/traces/UrbanSystems"
        self.urban_list = self.output_dir + "/urban_systems_list.txt"
        if os.path.isfile(self.urban_list):
            os.remove(self.urban_list)
        with open(str(self.urban_list), "w") as outfile:
            for num in xrange(self.iterations):
                for path, dirs, files in os.walk(urban_traces_dir):
                    for f in files:
                        f = os.path.join(path, f)
                        if f.endswith(".pcap") or f.endswith(".cap"):
                            if os.path.isfile(f):
                                outfile.write(f + '\n')
                            else:
                                print "not a file"
        outfile.close()


    def run_command(self, cmd):
        """ Runs command 'cmd' in linux terminal """
        subprocess.call(cmd, shell=True)

    def run_flowtool_redirect(self, file_list):
        """ Allows you to redirect the flowtool
            log files to the path of your choice """
        if os.path.isfile(file_list):
            try:
                print "Running flowtool"
                cmd = self.flowtool_path
                cmd += " -D " + self.capreader_path
                cmd += " -f " + file_list
                cmd += " -m 5"
                cmd += " -O " + str(self.output_dir)
                print str(self.output_dir)
                self.run_command(cmd)
            except Exception, error_msg:
                print error_msg

    def graph_results(self):
        """ Graphs results from the flowtool memory log file """
        cmd = "/root/qasvn/scripts2/NAVL/"
        cmd += "graph_lab_stability.sh %s" % self.output_dir
        cmd += "/full_list.txt.mem.log"
        cmd += " " + self.output_dir + "/lab_stability"
        subprocess.call(cmd, shell=True)

    def graph_urban(self):
        """ Graphs results from flowtol memory log file
        from urban traces """
        cmd = "/root/qasvn/scripts2/NAVL/"
        cmd += "graph_lab_stability.sh %s" % self.output_dir
        cmd += "/urban_systems_list.txt.mem.log"
        cmd += " " + self.output_dir + "/lab_stability"
        subprocess.call(cmd, shell=True)


    def run(self):
        self.extract_build()
        print "Creating file list"
        self.create_file_list()
        self.create_file_list_urban()
        print "File lists created"
        print "Running flowtool on full list"
        self.run_flowtool_redirect(self.full_list)
        print "Running flowtool on urban list"
        self.run_flowtool_redirect(self.urban_list)
        print "Graphing full list results"
        self.graph_results()
        print "Graphing urban list results"
        self.graph_urban()





if __name__ == "__main__":
    stabilityTest = LabStability(sys.argv[1], 1)
    stabilityTest.run()